package com.mulong.mall.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mulong.common.dao.mall.CustomerOrderDao;
import com.mulong.common.domain.pojo.mall.custom.CustomerOrderDetailInfo;
import com.mulong.common.domain.pojo.mall.custom.CustomerOrderDetailInfoQuery;
import com.mulong.common.enums.CustomerOrderStatus;
import com.mulong.common.exception.ErrorEnums;
import com.mulong.common.exception.MulongException;
import com.mulong.common.util.MulongUtil;
import com.mulong.mall.constants.Constants;
import com.mulong.mall.domain.bo.manager.*;
import com.mulong.mall.domain.param.manager.*;
import com.mulong.mall.domain.result.manager.*;
import com.mulong.mall.service.ManagerOrderService;
import com.mulong.mall.service.support.ManagerOrderSupport;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * ManagerOrderServiceImpl
 * 
 * @author mulong
 * @data 2021-06-21 14:08:32
 */
@Slf4j
@Service
public class ManagerOrderServiceImpl implements ManagerOrderService {
    @Autowired
    private CustomerOrderDao customerOrderDao;
    @Autowired
    private ManagerOrderSupport managerOrderSupport;

    /**
     * 客户订单列表
     * 
     * @author mulong
     */
    @Override
    public GetCustomerOrderByPageResult getCustomerOrderByPage(GetCustomerOrderByPageParam param) {
        CustomerOrderDetailInfoQuery query = new CustomerOrderDetailInfoQuery();
        query.setCustomizedOrderId(param.getCustomizedOrderId());
        query.setSku(param.getSku());
        query.setSupplierChannelId(param.getSupplierChannelId());
        query.setReceiverName(param.getReceiverName());
        query.setExpressNo(param.getExpressNo());
        query.setStatus(param.getStatus());
        if (StringUtils.isNotBlank(param.getCreateTimeBegin())) {
            query.setCreateTimeBegin(DateUtil.parse(param.getCreateTimeBegin(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(param.getCreateTimeEnd())) {
            query.setCreateTimeEnd(DateUtil.parse(param.getCreateTimeEnd(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(param.getFeedbackTimeBegin())) {
            query.setFeedbackTimeBegin(DateUtil.parse(param.getFeedbackTimeBegin(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(param.getFeedbackTimeEnd())) {
            query.setFeedbackTimeEnd(DateUtil.parse(param.getFeedbackTimeEnd(), "yyyy-MM-dd"));
        }
        query.setOrderBy("cod.`create_time` DESC");
        int pageNo = param.getPageNo() == null ? Constants.DEFAULT_PAGE_NO : param.getPageNo();
        int pageSize = param.getPageSize() == null ? Constants.DEFAULT_PAGE_SIZE : param.getPageSize();
        PageHelper.startPage(pageNo, pageSize, true);
        Page<CustomerOrderDetailInfo> page = (Page<CustomerOrderDetailInfo>) customerOrderDao.queryCustomerOrderDetailInfo(query);
        GetCustomerOrderByPageResult getCustomerOrderByPageResult = new GetCustomerOrderByPageResult(page.getPageNum(), page.getPageSize(), (int)page.getTotal());
        List<CustomerOrderDetailInfo> list = page.getResult();
        if (!CollectionUtils.isEmpty(list)) {
            getCustomerOrderByPageResult.setResult(list.stream().map(CustomerOrder::new).collect(Collectors.toList()));
        }
        return getCustomerOrderByPageResult;
    }

    /**
     * 下载客户订单
     * 
     * @author mulong 
     */
    @Override
    public ResponseEntity<byte[]> downloadCustomerOrder(DownloadCustomerOrderParam param) {
        String fileName = "客户订单.xls";
        // get data
        CustomerOrderDetailInfoQuery query = new CustomerOrderDetailInfoQuery();
        query.setCustomizedOrderId(param.getCustomizedOrderId());
        query.setSku(param.getSku());
        query.setSupplierChannelId(param.getSupplierChannelId());
        query.setReceiverName(param.getReceiverName());
        query.setExpressNo(param.getExpressNo());
        query.setStatus(param.getStatus());
        if (StringUtils.isNotBlank(param.getCreateTimeBegin())) {
            query.setCreateTimeBegin(DateUtil.parse(param.getCreateTimeBegin(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(param.getCreateTimeEnd())) {
            query.setCreateTimeEnd(DateUtil.parse(param.getCreateTimeEnd(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(param.getFeedbackTimeBegin())) {
            query.setFeedbackTimeBegin(DateUtil.parse(param.getFeedbackTimeBegin(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(param.getFeedbackTimeEnd())) {
            query.setFeedbackTimeEnd(DateUtil.parse(param.getFeedbackTimeEnd(), "yyyy-MM-dd"));
        }
        query.setOrderBy("cod.`create_time` DESC");
        List<CustomerOrderDetailInfo> records = customerOrderDao.queryCustomerOrderDetailInfo(query);
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            HSSFSheet sheet = workbook.createSheet(Constants.MANAGER_DOWNLOAD_CUSTOMER_ORDER_SHEET_NAME);            
            List<String> titles = Constants.MANAGER_DOWNLOAD_CUSTOMER_ORDER_SHEET_TITLE;
            MulongUtil.addTitle(workbook, sheet, titles);
            HSSFCellStyle defaultStyle = MulongUtil.getDefaultCellStyle(workbook);
            int lastRowNum = sheet.getLastRowNum();
            for (int j = 0; j < records.size(); j++) {
                CustomerOrderDetailInfo record = records.get(j);
                HSSFRow row = sheet.createRow(j + (lastRowNum + 1));
                managerOrderSupport.addRow(row, record, defaultStyle);
            }
            content = MulongUtil.toByteArray(workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

    /**
     * 下载客户已付款订单
     * 
     * @author mulong 
     */
    @Override
    public ResponseEntity<byte[]> downloadCustomerPaidOrder() {
        String fileName = "客户已付款订单.xls";
        // get data
        CustomerOrderDetailInfoQuery query = new CustomerOrderDetailInfoQuery();
        query.setStatus(CustomerOrderStatus.PAID.getCode());
        query.setOrderBy("cod.`create_time` DESC");
        List<CustomerOrderDetailInfo> records = customerOrderDao.queryCustomerOrderDetailInfo(query);
        // build content
        byte[] content = null;
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            HSSFSheet sheet = workbook.createSheet(Constants.MANAGER_DOWNLOAD_CUSTOMER_ORDER_SHEET_NAME);            
            List<String> titles = Constants.MANAGER_DOWNLOAD_CUSTOMER_ORDER_SHEET_TITLE;
            MulongUtil.addTitle(workbook, sheet, titles);
            HSSFCellStyle defaultStyle = MulongUtil.getDefaultCellStyle(workbook);
            int lastRowNum = sheet.getLastRowNum();
            for (int j = 0; j < records.size(); j++) {
                CustomerOrderDetailInfo record = records.get(j);
                HSSFRow row = sheet.createRow(j + (lastRowNum + 1));
                managerOrderSupport.addRow(row, record, defaultStyle);
            }
            content = MulongUtil.toByteArray(workbook);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            content = null;
        }
        if (content == null) {
            throw new MulongException(ErrorEnums.HANDLE_FAILED_TEMPLETE.format("导出数据异常"));
        }
        // build response
        return MulongUtil.buildDownloadResponse("application/octet-stream", fileName, content);
    }

}
